#include <kernel.h>
#include <clock.h>
#include <stm32f10x.h>

#include "board.h"

void systick_init(void)
{
	SysTick_Config(SystemCoreClock / TICK_SMALL);
	NVIC_SetPriority(SysTick_IRQn, 0xFF);
}

void __udelay(uint32_t us)
{
    uint32_t ticks;
    uint32_t told, tnow, tcnt = 0;
    uint32_t reload = SysTick->LOAD;

    ticks = us * reload / (1000000 / TICK_SMALL);
    told = SysTick->VAL;
    while (1)
    {
        tnow = SysTick->VAL;
        if (tnow != told)
        {
            if (tnow < told)
            {
                tcnt += told - tnow;
            }
            else
            {
                tcnt += reload - tnow + told;
            }
            told = tnow;
            if (tcnt >= ticks)
            {
                break;
            }
        }
    }
}

void borad_init(void)
{
	/* 设置中断分组为4 */
	NVIC_PriorityGroupConfig(NVIC_PriorityGroup_4);

	systick_init();

	mem_init((void *)HEAP_BEGIN, (void *)HEAP_END);
}

void hard_fault_handler(void)
{
	while(1);
}

void SysTick_Handler(void)
{
	tick_increase();
}
